<?php

namespace service;

use fast\Random;

class CouponService
{
    public function coupon_receive($id, $user_id, $coupon_type)
    {
        //设置过滤方法
        $coupon = model('app\api\model\wanlshop\Coupon')->get($id);
        if(!$coupon){
            return ['code'=>'FAIL','网络繁忙或优惠券不存在'];
        }
        // 查询此ID领取几张
        $myCouponCount = model('app\api\model\wanlshop\CouponReceive')
            ->where(['coupon_id' => $id, 'user_id' => $user_id])
            ->count();
        // 判断是否发完
        if($coupon['drawlimit'] != 0){
            if($myCouponCount >= $coupon['drawlimit']){
                return ['code'=>'FAIL','亲，您已领取了'.$myCouponCount.'张，不能在领了！'];
            }
        }
        // 判断是否超出总数量
        if($coupon['grant'] != '-1'){
            if($coupon['alreadygrant'] >= intval($coupon['grant'])  || $coupon['surplus'] == 0){
                return ['code'=>'FAIL','亲，您来晚了，刚刚被抢完！'];
            }
        }
        // 判断优惠券是否过期
        if($coupon['pretype'] == 'fixed'){
            if(time() > strtotime($coupon['enddate'])){
                return ['code'=>'FAIL','此张优惠券已经过期了'];
            }
        }
        // 领取优惠券并保留备份
        $result = model('app\api\model\wanlshop\CouponReceive');
        $result->state = 1;
        $result->coupon_id = $id;
        $result->coupon_no = Random::alnum(16);
        $result->user_id = $user_id;
        $result->shop_id = $coupon['shop_id'];
        $result->type = $coupon['type'];
        $result->name = $coupon['name'];
        $result->userlevel = $coupon['userlevel'];
        $result->usertype = $coupon['usertype'];
        $result->price = $coupon['price'];
        $result->discount = $coupon['discount'];
        $result->limit = $coupon['limit'];
        $result->rangetype = $coupon['rangetype'];
        $result->range = $coupon['range'];
        $result->pretype = $coupon['pretype'];
        $result->validity = $coupon['validity'];
        $result->startdate = $coupon['startdate'];
        $result->enddate = $coupon['enddate'];
        $result->coupon_type = $coupon_type;
        $result->save();
        if($result){
            if($coupon['grant'] != '-1'){
                // 剩余数量
                $data['surplus'] = $coupon['surplus'] - 1;
                // 即将过期，强制失效
                if($coupon['surplus'] == 1){
                    $data['invalid'] = 1;
                }
            }
            $data['alreadygrant'] = $coupon['alreadygrant'] + 1;
            // 更新优惠券领取+1
            $coupon->allowField(true)->save($data);
            return ['code'=>'success','赠送成功'];
        }else{
            return ['code'=>'FAIL','赠送失败'];
        }
    }

}